package special;

import com.sun.org.apache.bcel.internal.generic.NEW;
import jdk.internal.dynalink.linker.LinkerServices;

public class StreamChecker2 {
    private TrieNode root = new TrieNode();
    private StringBuilder input = new StringBuilder();
    public StreamChecker2(String[] words) {
        for (String word : words) {
            word = new StringBuilder(word).reverse().toString();
            TrieNode cur = root;
            for (int i = 0; i < word.length(); i++) {
                char c = word.charAt(i);
                int index = c - 'a';
                if (cur.children[index] == null){
                    cur.children[index] = new TrieNode();
                    if (i == word.length() - 1){
                        cur.children[index].isEnd = true;
                    }
                    cur = cur.children[index];
                }else {
                    if (i == word.length() - 1){
                        cur.children[index].isEnd = true;
                    }
                    cur = cur.children[index];
                }
            }
        }
    }

    public boolean query(char letter) {
        input.append(letter);
        TrieNode cur = root;
        for (int i = input.length() - 1; i >= 0; i--) {
            int index = input.charAt(i) - 'a';
            if (cur.children[index] == null){
                return false;
            }
            if (cur.children[index].isEnd)
                return true;
            cur = cur.children[index];
        }
        return false;
    }



    static class TrieNode {
        TrieNode[] children;
        boolean isEnd;
        public TrieNode(){
            children = new TrieNode[26];
        }
    }
}
